<template>
  <PageWrapper>
    <a-modal width="100%" title="商户详情" v-model:visible="showModal" fullscreen>
      <template #footer>
        <a-button @click="showModal = false">取消</a-button>
        <a-button type="primary" @click="submitHandle">确定</a-button>
      </template>

      <a-form
        :disabled="modalType === ModalType.VIEW"
        label-align="left"
        ref="formRef"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        :model="formData"
        label-placement="left"
      >
        <a-card :bordered="false" class="mt-3 proCard" title="商户信息">
          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item label="商户名称" field="merchantName" :rules="rules.merchantName">
                <a-input v-model="formData.merchantName" placeholder="输入商户名称" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item label="手机号码" field="mobile" :rules="rules.mobile">
                <a-input v-model="formData.mobile" placeholder="输入手机号码" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item label="美团店铺ID" field="mtStoreId" :rules="rules.mtStoreId">
                <a-input v-model="formData.mtStoreId" placeholder="输入美团店铺ID" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item label="门店接单电话" field="poiMobile" :rules="rules.poiMobile">
                <a-input v-model="formData.poiMobile" placeholder="输入门店接单电话" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item label="门店定位" field="poi">
                <a-input v-model="formData.poi" placeholder="输入门店定位" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item label="门店地址" field="poiAddress" :rules="rules.poiAddress">
                <a-input v-model="formData.poiAddress" placeholder="输入门店地址" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item label="店铺类型" field="poiType">
                <a-select v-model="formData.poiType" placeholder="请选择店铺类型">
                  <a-option :value="1">鲜花</a-option>
                  <a-option :value="2">蛋糕</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <a-card :bordered="false" class="mt-3 proCard" title="结算卡信息">
          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item label="开户人姓名" field="accountHolder" :rules="rules.accountHolder">
                <a-input v-model="formData.accountHolder" placeholder="请输入开户人姓名" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item label="银行卡号" field="accountCard" :rules="rules.accountCard">
                <a-input v-model="formData.accountCard" placeholder="请输入银行卡号" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item label="银行卡开户行" field="accountBank" :rules="rules.accountBank">
                <a-input v-model="formData.accountBank" placeholder="请输入银行卡开户行" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <a-card :bordered="false" class="mt-3 proCard" title="图片信息">
          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item
                :label-col-props="{ span: 24 }"
                label-align="left"
                label="营业执照照片（请勿截屏截图）"
                field="businessLicense"
                :rules="rules.businessLicense"
              >
                <BasicUpload
                  :disabled="modalType === ModalType.VIEW"
                  :action="`${uploadUrl}`"
                  name="file"
                  :width="100"
                  :height="100"
                  v-model:value="formData.businessLicense"
                />
              </a-form-item>
            </a-col>
            <a-col v-if="showModal" :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item
                :label-col-props="{ span: 24 }"
                label-align="left"
                label="食品经营许可证照片（请勿截屏截图）"
                field="foodBusinessLicense"
              >
                <BasicUpload
                  :disabled="modalType === ModalType.VIEW"
                  :action="`${uploadUrl}`"
                  name="file"
                  :width="100"
                  :height="100"
                  v-model:value="formData.foodBusinessLicense"
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item
                :label-col-props="{ span: 24 }"
                label-align="left"
                label="法人身份证照片（正反两张）"
                field="legalManId"
                :rules="rules.legalManId"
              >
                <BasicUpload
                  :disabled="modalType === ModalType.VIEW"
                  :action="`${uploadUrl}`"
                  name="file"
                  :width="100"
                  :height="100"
                  v-model:value="formData.legalManId"
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item
                :label-col-props="{ span: 24 }"
                label-align="left"
                label="法人手持身份证照片（正反两张）"
                field="legalManTakeId"
                :rules="rules.legalManTakeId"
              >
                <BasicUpload
                  :disabled="modalType === ModalType.VIEW"
                  :action="`${uploadUrl}`"
                  name="file"
                  :width="100"
                  :height="100"
                  v-model:value="formData.legalManTakeId"
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item
                :label-col-props="{ span: 24 }"
                label-align="left"
                label="实体门头照（请勿截屏截图）"
                field="storePhoto"
                :rules="rules.storePhoto"
              >
                <BasicUpload
                  :disabled="modalType === ModalType.VIEW"
                  :action="`${uploadUrl}`"
                  name="file"
                  :width="100"
                  :height="100"
                  v-model:value="formData.storePhoto"
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="6">
              <a-form-item
                :label-col-props="{ span: 24 }"
                label-align="left"
                label="店内环境照（请勿截屏截图）"
                field="envirPhoto"
              >
                <BasicUpload
                  :disabled="modalType === ModalType.VIEW"
                  :action="`${uploadUrl}`"
                  name="file"
                  :width="100"
                  :height="100"
                  v-model:value="formData.envirPhoto"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>
    </a-modal>

    <a-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @advanced="actionRef.redoHeight()" />
    </a-card>

    <a-card :bordered="false" class="proCard">
      <BasicTable :columns="columns" :request="loadDataTable" row-key="id" ref="actionRef">
        <template #tableTitle>
          <a-button type="primary" @click="addTable(ModalType.ADD)">
            <template #icon>
              <PlusOutlined class="arco-icon" />
            </template>
            新建
          </a-button>
        </template>
        <template #poiType="{ record }">
          <span v-if="record.poiType === 1">鲜花</span>
          <span v-if="record.poiType === 2">蛋糕</span>
        </template>
        <template #actions="{ record }">
          <a-button
            @click="downloadImages(record)"
            style="margin: 0 10px"
            type="primary"
            size="mini"
          >
            下载图片
          </a-button>
          <a-button
            style="margin: 0 10px"
            type="primary"
            size="mini"
            @click="addTable(ModalType.EDIT, record)"
          >
            编辑
          </a-button>
          <a-button
            style="margin: 0 10px"
            type="primary"
            size="mini"
            @click="addTable(ModalType.VIEW, record)"
          >
            查看
          </a-button>
        </template>
        <template #toolbar>
          <a-button type="primary" @click="actionRef.reload()">刷新数据</a-button>
        </template>
      </BasicTable>
    </a-card>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { BasicUpload } from '@/components/Upload';

  import { getBusinessList, merchantInster, merchantUpdate } from '@/api/business/index';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { PageWrapper } from '@/components/Page';
  import { BasicColumn, BasicTable } from '@/components/Table';
  import { useGlobSetting } from '@/hooks/setting';
  import { Message } from '@arco-design/web-vue';
  import { PlusOutlined } from '@vicons/antd';
  import { ref } from 'vue';
  const globSetting = useGlobSetting();
  const { uploadUrl } = globSetting;
  const schemas: FormSchema[] = [
    {
      field: 'mobile',
      component: 'Input',
      label: '手机号码',
      componentProps: {
        allowClear: true,
      },
    },
    {
      field: 'merchantName',
      component: 'Input',
      label: '商户名称',
      componentProps: {
        allowClear: true,
      },
    },
    {
      field: 'mtStoreId',
      component: 'Input',
      label: '美团店铺ID',
      componentProps: {
        allowClear: true,
      },
    },
    {
      field: 'createDate_begin',
      component: 'DatePicker',
      label: '开始时间',
      wrapperColStyle: { width: '100%' },
      //defaultValue: 1183135260000,
      componentProps: {
        clearable: true,
      },
    },
    {
      field: 'createDate_end',
      component: 'DatePicker',
      label: '结束时间',
      wrapperColStyle: { width: '100%' },
      //defaultValue: 1183135260000,
      componentProps: {
        clearable: true,
      },
    },
  ];

  enum ModalType {
    ADD = 'add',
    EDIT = 'edit',
    VIEW = 'view',
  }

  const columns: BasicColumn[] = [
    {
      title: '序号',
      dataIndex: 'id',
      width: 70,
    },
    {
      title: '商户名称',
      dataIndex: 'merchantName',
      width: 200,
    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
      width: 200,
    },
    // {
    //   title: '平台ID',
    //   dataIndex: 'mtStoreId',
    // },
    {
      title: '美团店铺ID',
      dataIndex: 'mtStoreId',
      width: 200,
    },
    {
      title: '商户类型',
      slotName: 'poiType',
      width: 120,
    },
    {
      title: '门店定位',
      dataIndex: 'poiAddress',
      ellipsis: true,
      tooltip: true,
      width: 200,
    },
    {
      title: '开户人姓名',
      dataIndex: 'accountHolder',
      width: 120,
    },
    {
      title: '银行卡号',
      dataIndex: 'accountCard',
      width: 200,
    },
    {
      title: '开户行',
      dataIndex: 'accountBank',
      width: 160,
    },
    {
      title: '提交时间',
      width: 180,
      dataIndex: 'createDate',
    },
    {
      title: '操作',
      width: 260,
      slotName: 'actions',
      fixed: 'right',
    },
  ];

  const rules = {
    merchantName: [
      {
        required: true,
        message: '请输入商户名称',
        trigger: ['blur', 'change'],
      },
    ],
    mobile: [
      {
        required: true,
        message: '请输入手机号码',
        trigger: ['blur', 'change'],
      },
    ],
    mtStoreId: [
      {
        required: true,
        message: '请输入美团店铺ID',
        trigger: ['blur', 'change'],
      },
    ],
    poiMobile: [
      {
        required: true,
        message: '请输入门店接单电话',
        trigger: ['blur', 'change'],
      },
    ],
    poiAddress: [
      {
        required: true,
        message: '请输入门店地址',
        trigger: ['blur', 'change'],
      },
    ],
    accountHolder: [
      {
        required: true,
        message: '请输入开户人姓名',
        trigger: ['blur', 'change'],
      },
    ],
    accountCard: [
      {
        required: true,
        message: '请输入银行卡号',
        trigger: ['blur', 'change'],
      },
    ],
    accountBank: [
      {
        required: true,
        message: '请输入银行开户行',
        trigger: ['blur', 'change'],
      },
    ],
    // businessLicense: [
    //   {
    //     required: true,
    //     message: '请上传营业执照照片',
    //     trigger: ['blur', 'change'],
    //   },
    // ],
    // legalManId: [
    //   {
    //     required: true,
    //     message: '请上传法人身份证照片',
    //     trigger: ['blur', 'change'],
    //   },
    // ],
    // legalManTakeId: [
    //   {
    //     required: true,
    //     message: '请上传法人手持身份证照片',
    //     trigger: ['blur', 'change'],
    //   },
    // ],
    // storePhoto: [
    //   {
    //     required: true,
    //     message: '请上传实体门头照',
    //     trigger: ['blur', 'change'],
    //   },
    // ],
  };

  const formRef: any = ref(null);
  const actionRef = ref();
  const showModal = ref(false);
  const modalType = ref<ModalType>(ModalType.ADD);

  const formData = ref({
    id: undefined,
    poi: '',
    accountBank: '',
    accountCard: '',
    accountHolder: '',
    businessLicense: '',
    envirPhoto: '',
    foodBusinessLicense: '',
    legalManId: '',
    legalManTakeId: '',
    merchantName: '',
    mobile: '',
    mtStoreId: '',
    password: '',
    poiAddress: '',
    poiLat: 0,
    poiLnt: 0,
    poiMobile: '',
    poiType: 1,
    remark: '',
    storePhoto: '',
  });

  const [register, {}] = useForm({
    labelColProps: {
      span: 6,
    },
    wrapperColProps: {
      span: 18,
    },
    labelWidth: 90,
    layout: 'inline',
    rowProps: { gutter: [8, 8] },
    colProps: {
      xs: 24,
      sm: 24,
      md: 12,
      lg: 8,
      xl: 6,
    },
    schemas,
  });

  function downloadImages(row) {
    try {
      const { apiUrl, urlPrefix1 } = globSetting;
      location.href = `${apiUrl}${urlPrefix1}/merchant/downMerchantData/${row.uuid}`;
    } catch (error) {
      console.log(error);
    }
  }

  function addTable(type: ModalType, row?) {
    formRef.value.clearValidate();
    formRef.value.resetFields();

    formData.value.foodBusinessLicense = '';
    formData.value.envirPhoto = '';
    formData.value.id = undefined;

    modalType.value = type;
    showModal.value = true;

    if (type !== ModalType.ADD) {
      const tempRow = JSON.parse(JSON.stringify(row));
      formData.value = tempRow;
      if (tempRow.poiLat && tempRow.poiLnt) {
        formData.value.poi = `${tempRow.poiLat},${tempRow.poiLnt}`;
      }
    }
  }

  const loadDataTable = async (res) => {
    const { pageSize, page } = res;
    const response = await getBusinessList(res, { pageSize: pageSize, pageNum: page });
    return {
      totalCount: response.totalCount,
      list: response.list,
    };
  };

  function handleSubmit(values: Recordable) {
    if (values) {
      actionRef.value.reload(values);
    }
  }

  async function submitHandle() {
    try {
      await formRef.value.validate();
      const params = {
        poiLat: formData.value.poi ? formData.value.poi.split(',')[0] : '',
        poiLnt: formData.value.poi ? formData.value.poi.split(',')[1] : '',
      };
      if (modalType.value === ModalType.ADD) {
        await merchantInster({ ...formData.value, ...params });
      }
      if (modalType.value === ModalType.EDIT) {
        await merchantUpdate({ ...formData.value, ...params });
      }
      actionRef.value.reload();
      Message.success('操作成功');
      showModal.value = false;
    } catch (error) {
      console.log(error);
    }
  }
</script>

<style lang="less" scoped>
  :deep(.arco-picker) {
    width: 100% !important;
  }
</style>
